package example.demo.netty.channelHandler;

import com.alibaba.fastjson.JSON;
import example.demo.netty.JsonMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.util.List;

/**
 * https://blog.csdn.net/weixin_43213517/article/details/110111326
 * 【Netty报错:】XXXDecoder.decode() did not read anything but decoded a message.
 */
public class FastJsonDecoder extends ByteToMessageDecoder {
    //    @Override
//    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//        String json = in.toString(CharsetUtil.UTF_8);
//        String[] split = json.split("}");
//        json = split[split.length - 1] + "}";
//        JsonMessage jsonObj = JSON.parseObject(json, JsonMessage.class);
////        ReferenceCountUtil.release(in);
//        out.add(jsonObj);
//    }
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int len = in.readableBytes();
        if (len == 0) {
            return;
        }
        byte[] arr = new byte[len];
        in.readBytes(arr, 0, len);
        JsonMessage jsonMessage = JSON.parseObject(new String(arr), JsonMessage.class);
        out.add(jsonMessage);
    }
}
